#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author:zhangcong
# Email:zc_92@sina.com


from django.shortcuts import render
from webadmin.views_dir import pub

from django.http import JsonResponse

from datetime import datetime

from webadmin.views_dir.mongo_oper import get_db_obj
from bson.objectid import ObjectId


# 权限管理
@pub.is_login
def rights_management(request):

    if "pageNum" in request.POST:
        pageNum = int(request.POST.get("pageNum"))
    else:
        pageNum = 1

    if "numPerPage" in request.POST:
        numPerPage = int(request.POST.get("numPerPage"))
    else:
        numPerPage = 20

    rights_objs_all = get_db_obj().rights.find()
    count = rights_objs_all.count()
    rights_objs = rights_objs_all.skip(pageNum * numPerPage - numPerPage).limit(numPerPage)

    # 所有用户的信息
    user_data = {}
    for i in get_db_obj().user.find({}, {"_id": 1, "username": 1}):
        user_data[i["_id"]] = i["username"]

    return render(request, 'webadmin/rights/rights_management.html', locals())


@pub.is_login
def rights_management_oper(request, oper_type, o_id):

    user_id = request.session['user_id']
    response = pub.BaseResponse()

    if request.method == "POST":
        # 添加
        if oper_type == "add":
            print(request.POST)

            name = request.POST.get('name')
            url = request.POST.get('url')
            p_id = request.POST.get('p_id')

            if not response.statusCode and not name.strip():
                response.statusCode = 300
                response.message = "权限名称不能为空"

            if not response.statusCode and not url.strip():
                response.statusCode = 300
                response.message = "权限url不能为空"

            # 判断权限名称是否存在
            if not response.statusCode:
                rights_obj = get_db_obj().rights.find_one({"name": name})
                if rights_obj:
                    response.statusCode = 300
                    response.message = "权限名称已存在"

            if not response.statusCode:
                get_db_obj().rights.insert({
                        "_id": str(ObjectId()),
                        "name": name,
                        "url": url,
                        "p_id": p_id,
                        "status": "1",
                        "create_user_id": user_id,
                        "create_date": datetime.now()
                    })

                response.statusCode = 200
                response.message = "添加成功"

        # 修改
        elif oper_type == "update":

            name = request.POST.get('name')
            url = request.POST.get('url')
            p_id = request.POST.get('p_id')
            status = request.POST.get("status")

            if not response.statusCode and not name.strip():
                response.statusCode = 300
                response.message = "权限名称不能为空"

            if not response.statusCode and not url.strip():
                response.statusCode = 300
                response.message = "权限url不能为空"

            # 判断权限名称是否存在
            if not response.statusCode:
                rights_obj = get_db_obj().rights.find_one({"name": name, "_id": {"$ne": o_id}})
                if rights_obj:
                    response.statusCode = 300
                    response.message = "权限名称已存在"

            if not response.statusCode:
                get_db_obj().rights.update(
                    {"_id": o_id},
                    {"$set": {
                        "name": name,
                        "url": url,
                        "p_id": p_id,
                        "status": status
                    }}
                )

                response.statusCode = 200
                response.message = "修改成功"

        # 删除
        elif oper_type == "del":

            # 判断一下该权限是否有子权限
            rights_obj = get_db_obj().rights.find_one({"p_id": o_id})
            if rights_obj:
                response.statusCode = 300
                response.message = "删除失败,该权限下还含有子权限"
                response.callbackType = None
            else:
                get_db_obj().rights.remove({"_id": o_id})

                response.statusCode = 200
                response.message = "删除成功"
                response.callbackType = None

        return JsonResponse(response.__dict__)

    else:
        # 添加
        if oper_type == "add":

            rights_list = get_db_obj().rights.find({}, {"name": 1, "_id": 1})

            return render(request, 'webadmin/rights/rights_management_modal_add.html', locals())

        # 修改
        elif oper_type == "update":
            rights = get_db_obj().rights.find_one({"_id": o_id})
            rights_list = get_db_obj().rights.find({"_id": {"$ne": o_id}}, {"name": 1, "_id": 1})
            return render(request, 'webadmin/rights/rights_management_modal_update.html', locals())
